package com.liang.maogouyuyin.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.liang.maogouyuyin.TheBaseApplication
import com.liang.maogouyuyin.databinding.ActivityWebBinding
import com.liang.maogouyuyin.ui.viewmodel.PetMenuViewModel

class WebActivity : AppCompatActivity() {

    private lateinit var binding: ActivityWebBinding

    private lateinit var petMenuViewModel: PetMenuViewModel

    private var url = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityWebBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initData()
        initView()
        initClick()
        updateUI()
    }

    override fun onDestroy() {
        binding.web.clearHistory()
        binding.web.clearCache(true)
        super.onDestroy()
    }

    private fun initData() {
        petMenuViewModel = TheBaseApplication.getInstance().petMenuViewModel
        url = intent.getStringExtra("url")!!
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initView() {
        binding.webTitle.text = intent.getStringExtra("title")
        binding.web.settings.javaScriptEnabled = true
        binding.web.settings.domStorageEnabled = true
        when (intent.getIntExtra("type", 0)) {
            0 -> petMenuViewModel.getVarietyDetail(url)
            1 -> petMenuViewModel.getTrainingArticle(url)
            2 -> petMenuViewModel.getAnimalArticle(url)
        }

    }

    private fun initClick() {
        binding.webToolBar.setNavigationOnClickListener {
            finish()
        }
    }

    private fun updateUI() {
        petMenuViewModel.varietyDetail.observe(this) {
            binding.web.loadDataWithBaseURL("https://www.chongwy.com$url", it, "text/html", "UTF-8", null)
        }

        petMenuViewModel.animalArticle.observe(this) {
            binding.web.loadDataWithBaseURL(url, it, "text/html", "UTF-8", null)
        }

        petMenuViewModel.trainingArticle.observe(this) {
            binding.web.loadDataWithBaseURL(url, it, "text/html", "UTF-8", null)
        }
    }
}